import { stat } from "fs"

const state = {
    articleList: [],
    articleTotal: 0,
    articleId: null,
    groupId: -1,
    avatar: '',
    model:'list'
}

const mutations = {
    setArticles: (state, { articleList, articleTotal }) => {
        state.articleList = articleList
        state.articleTotal = articleTotal
    },
    setArticleId: (state, articleId) => {
        state.articleId = articleId
    },
    setGroupId: (state, groupId) => {
        state.groupId = groupId
    },
    setTotal: (state, articleTotal) => {
        state.articleTotal = articleTotal
    },
    setModel: (state, model) => {
        state.model = model
    }
}

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { account, pwd } = userInfo
        return new Promise((resolve, reject) => {
            userLoginApi({ account: account.trim(), pwd: pwd }).then(response => {
                if (response.code == 200) {
                    const { data } = response;
                    commit('SET_TOKEN', data.token)
                    commit('SET_NAME', data.userName)
                    commit('SET_AVATAR', data.avatar)
                    setUser(data.userName)
                    setToken(data.token)
                    resolve()
                }
            }).catch(error => {
                reject(error)
            })
        })
    },

    // get user info
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo(state.token).then(response => {
                const { data } = response

                if (!data) {
                    reject('Verification failed, please Login again.')
                }

                const { name, avatar } = data

                commit('SET_NAME', name)
                commit('SET_AVATAR', avatar)
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            removeToken()
            removeUser()
            resetRouter()
            resolve()
            // logout(state.token).then(() => {
            //   commit('SET_TOKEN', '')
            //   removeToken()
            //   resetRouter()
            //   resolve()
            // }).catch(error => {
            //   reject(error)
            // })
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            removeToken()
            removeUser()
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}